import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from "@/views/Main";
import Home from "@/views/Home";
import GoodManage from "@/views/GoodManage";
import Users from "@/views/Users";
import Login from "@/views/Login";
import UserCenter from '@/views/UserCenter'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: {
            path: '/login'
        }
    },
    {
        path: '/home',
        name: 'Main',
        component: Main,
        children: [
            {path: '', name: 'Home', component: Home},
            {path: 'goodmanage', name: 'GoodManage', component: GoodManage},
            {path: 'users', name: 'Users', component: Users}
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/usercenter',
        name: 'UserCenter',
        component: UserCenter
    }
]

const router = new VueRouter({
    routes
})
//因路由重定向后没有捕获catch信息导致报错，消除报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
    const toPathWithToken = ['/home', '/home/goodmanage', '/home/users', '/usercenter']

    if (toPathWithToken.indexOf(to.path) === '-1') {
        if (window.localStorage.getItem('TOKEN') === 'braea qwe27834$@#$6ZDF234') {
            next();
        } else (
            next({path: '/login'})
        )
    } else if (to.path === '/' && window.localStorage.getItem('TOKEN') === 'braea qwe27834$@#$6ZDF234') {
        next('/home');
    } else {
        next();
    }

})

export default router
